
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        this.bindBtnTui();
        this.bindBtnPlus();
        this.bindTimer();
        this.bindBtnCancel();
        this.bindBtnCaiStart();
        this.bindBtnCaiDone();
        this.bindModalHide();
        this.bindBtnStuffOrder();
        this.bindBtnGuestPayByQr();
        this.bindBtnTuiAll();
        this.bindBtnAddCaiQuick();
        this.bindBtnZhuoHaoShow();
        this.bintBtnZhuoHaoClick('#zhuohao-list-box a.active');
        this.bindBtnZhuoHaoKaiTai('#zhuohao-list-box a.empty');
        this.bindBtnCaiQuery();
        this.bindSearchZhuoHaoChange();
        this.bindYDUserDaoDian();
        this.bindYDUserCheck();
        this.initCurZhuoHaoShow();
    },
    bindYDUserDaoDian: function() {
        var self    = this;
        $('a.btn-yd-user-daodian').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('设置用户到店桌号');
            $('#modal-body').html($('#yd-zhuohao-list-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/zhuohao/auselist',
                {},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    if(1 > response.data.length) {
                        return HHJsLib.warn('桌位已满，请客人稍等一下！');
                    }
                    var opt     = '<option value="">请选择桌号</option>';
                    for(var ele in response.data) {
                        var item= response.data[ele];
                        opt     += '<option value="' + item.id + '">桌号：' + item.name + '</option>';
                    }
                    $('#yd-zhuohao-list').html(opt);
                    $('#myModal').modal('show');
                    self.bindBtnYuDingModalConfirm(id);
                }
            );
        });
    },
    bindBtnYuDingModalConfirm: function(id) {
        var self    = this;
        $('#btn-tui-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#yd-zhuohao-list', '桌号');
                HJZCommon.isLoading     = true;
                var code                = $('#yd-zhuohao-list').val();
                $.getJSON(
                    queryUrl + 'admin/yuding/auserdaodian',
                    {id: id, code: code},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        $('#myModal').modal('hide');
                        HHJsLib.succeed('确认成功！订单已经移动到在店客人中，正在加载，请稍等...');
                        setTimeout(function() {
                            window.location.href    = queryUrl + 'admin/diancan?id=' + id + '&code=' + code;
                        }, 500);
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindYDUserCheck: function() {
        $('a.btn-yd-check').click(function() {
            var $this   = $(this);
            var id      = $this.attr('data-id');
            if(!confirm('确定客人已经确认了？')) {
                return false;
            }
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/yuding/ausersure',
                {id: id},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#lable-ren-' + id).removeClass('hide');
                    HHJsLib.succeed('确认成功！');
                }
            );
        });
    },
    bindSearchZhuoHaoChange: function() {
        $('#search-zhuohao').bind('keyup', function() {
            var val = $(this).val();
            var ids = [];
            if(!val) {
                $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').show();
                return;
            }
            val     = val.toUpperCase();
            $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').hide();
            for(var ele in orderMap) {
                if(0 > orderMap[ele].id.toString().indexOf(val)) {
                    continue;
                }
                $('#zhuohao-list-box div.zhuohao-item-box-' + orderMap[ele].id)
                .addClass('search-item').show();
            }
        }).bind('keydown', function(e) {
            if (e.keyCode != 13) {
                return;
            }
            $('#zhuohao-list-box div.zhuohao-item-box.search-item > a').first().click();
        }).bind('blur', function() {
            $(this).val('');
            $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').show();
        });
    },
    bindBtnZhuoHaoKaiTai: function() {
        var self    = this;
        $('#btn-new-order').click(function() {
            $('#modal-title').html('新预订订单');
            $('#modal-body').html($('#yuding-list-tpl').html());
            $('#modal-footer').html($('#kaitai-footer-tpl').html());
            $("#yd-time").datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss', 
                language: "zh-CN", 
                autoclose: true,
                todayBtn: true
            });
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/zhuohao/auselist',
                {},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#myModal').modal('show');
                    if(1 > response.data.length) {
                        return HHJsLib.warn('桌位已满，请客人稍等一下！');
                    }
                    var opt     = '<option value="">请选择桌号</option>';
                    for(var ele in response.data) {
                        var item= response.data[ele];
                        opt     += '<option value="' + item.id + '">桌号：' + item.name + '</option>';
                    }
                    $('#yd-zhuohao').html(opt);
                    self.bindBtnKaiTaiConfirm();
                }
            );
        });
    },
    bindBtnKaiTaiConfirm: function() {
        var self    = this;
        $('#btn-tui-confrim').click(function() {
            HJZCommon.isLoading = true;
            HHJsLib.info('正在努力操作中，请稍等...');
            $.getJSON(
                queryUrl + 'admin/order/anewyuding',
                {
                    people: $('#kt-total-people').val(), 
                    sure: $('#yd-sure').val(), 
                    zhuohao: $('#yd-zhuohao').val(), 
                    time: $('#yd-time').val(), 
                    phone: $('#yd-phone').val()
                },
                function(response) {
                    HJZCommon.isLoading = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('添加成功，正在加载中...');
                    window.location.href    = queryUrl + "admin/yuding?add=1&id=" + response.id;
                }
            );
        });
    },
    bintBtnZhuoHaoClick: function(dom) {
        var title           = $('title').text();
        $(dom).click(function() {
            var $this       = $(this);
            var id          = $this.attr('data-id');
            $('#zhuohao-list-box a.current').removeClass('current');
            $this.addClass('current');
            history.pushState({page: 1}, title, queryUrl + 'admin/yuding?id=' + id);
            if(0 == id) {
                return;
            }
            $('#order-list-box div.show').hide().removeClass('show');
            $('#zhuo-hao-order-box-' + id).addClass('show').show();
        });
    },
    initCurZhuoHaoShow: function() {
        if(curOrderId) {
            $('#zhuo-hao-item-' + curOrderId).click();
            if(add) {
                $('#btn-add-cai-' + curOrderId).click();
            }
        } else {
            this.setFirstActiveZhuoHao();
        }
    },
    bindBtnZhuoHaoShow: function() {
        $('#filter-search-box a.btn-area-show').click(function() {
            var id  = $(this).attr('data-id');
            $('#filter-search-box a.btn-area-show').removeClass('btn-primary');
            $(this).addClass('btn-primary');
            if(id <= 0) {
                $('#zhuohao-list-box div.zhuohao-item-box').show();
                return;
            }
            $('#zhuohao-list-box div.zhuohao-item-box').hide();
            $('#zhuohao-list-box div.area-' + id).show();
            return;
        });
    },
    bindBtnSetTotalPeople: function() {
        $('a.set-total-people').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('人数设置');
            $('#modal-body').html($('#total-people-body-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            $('#myModal').modal('show');
        });
    },
    bindBtnAddCaiQuick: function() {
        var self    = this;
        $('#btn-add-cai-quick').click(function() {
            $('#add-cai-modal').modal('hide');
            $.getJSON(
                queryUrl + 'admin/goodscategory/alist',
                {},
                function(response){
                    if(response.rs == false){
                        return HHJsLib.warn(response.message);
                    }
                    var html    = '<option value="">请选择</option>';
                    var content = html;
                    var cate    = response.data.category;
                    var list    = response.data.printer;
                    for(var i in list){
                        var item = list[i];
                        content    += '<option value="' + item.id + '">' + item.name + '</option>';
                    }
                    for(var i in cate){
                        var item = cate[i];
                        html    += '<option value="' + item.id + '">' + item.name + '</option>';
                    }
                    var tpl     = $('#add-cai-body-tpl').html();
                    tpl         = tpl.replace(/{category}/ig, html).replace(/{printer}/ig, content);
                    $('#modal-title').html('加自定义菜品');
                    $('#modal-body').html(tpl);
                    $('#modal-footer').html($('#tui-footer-tpl').html());
                    $('#myModal').modal('show');
                    self.bindBtnAddCaiQuickConfirm();
                }
            );
        });
    },
    bindBtnAddCaiQuickConfirm: function(){
      var self = this;
      $('#btn-tui-confrim').click(function(){
          try{
              HHJsLib.isEmptyByDom('#cai-name', '菜名');
              HHJsLib.isEmptyByDom('#cai-cat', '菜品分类');
              HHJsLib.isEmptyByDom('#cai-price', '价格');
              HHJsLib.isEmptyByDom('#cai-printer', '对应打印机');
              var orderId = $('#cur-order-id').val();
              HHJsLib.isEmpty(orderId, '餐桌号');
              var name  = $('#cai-name').val();
              var catId = $('#cai-cat').val();
              var price = $('#cai-price').val();
              var printer = $('#cai-printer').val();
              $.getJSON(
                  queryUrl + 'admin/diancan/addcaiquick',
                  {name: name, cat_id: catId, price: price, printer: printer, order_id: orderId},
                  function(response){
                      if(response.rs == false){
                          return HHJsLib.warn(response.message);
                      }
                      HHJsLib.succeed('加菜成功！');
                      var data    = response.data;
                      var tpl     = $('#plus-goods-item-tpl').html();
                      tpl         = tpl.replace(/{order_goods_id}/ig, data.goods_id)
                          .replace(/{id}/ig, orderId)
                          .replace(/{name}/ig, data.name)
                          .replace(/{group_name}/ig, data.group_name)
                          .replace(/{price}/ig, data.price)
                          .replace(/{vip_price}/ig, data.vip_price)
                          .replace(/{src_price}/ig, data.src_price)
                          .replace(/{number}/ig, data.number)
                          .replace(/{order_id}/ig, orderId)
                          .replace(/{order_goods_id}/ig, data.id)
                          .replace(/{printer_id}/ig, data.printer_id)
                          .replace(/{printer_name}/ig, data.printer_name)
                          .replace(/{number}/ig, data.number)
                          .replace(/{discount}/ig, data.discount)
                          .replace(/{total_price}/ig, data.total_price);
                      $('#data-grid-box-' + orderId).find('tbody').prepend(tpl);
                      $('#item-total-number-' + orderId).html(data.total_number);
                      $('#item-total-amount-' + orderId).html(data.amount);
                      $('strong.src-amount-' + orderId + " span.amount").html(data.src_amount);
                      $('#item-total-src-amount-' + orderId).html(data.src_amount);
                      $('#item-pay-money-' + orderId).html(data.pay_money);
                      if(parseFloat(data.youhui) > 0){
                          $('#use-youhui-' + orderId).html('优惠：' + response.data.youhui + ' 元 ').show();
                      }else{
                          $('#use-youhui-' + orderId).hide();
                      }
                      self.bindResetPrint('#zd-od-item-' + data.goods_id + ' a.btn-reset-print');
                      self.bindBtnPrintCai('#zd-od-item-' + data.goods_id + ' a.btn-print-cai');
                      self.bindBtnTui();
                      $('#myModal').modal('hide');
                  }
              );
          }catch(e){
              return HHJsLib.warn(e);
          }
      });
    },
    bindBtnTuiAll: function() {
        $('a.btn-tui-all').click(function() {
            if(!confirm('确认要整桌退吗？')) {
                return;
            }
            var id  = $(this).attr('data-id');
            HJZCommon.isLoading = true;
            $.getJSON(
                queryUrl + 'admin/order/atuiall',
                {id: id},
                function(response) {
                    HJZCommon.isLoading = true;
                    if(false == response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('整桌退菜打印成功！');
                }
            );
        });
    },
    bindBtnGuestPayByQr: function() {
        $('#btn-guest-pay-qr').click(function() {
            var src     = $(this).attr('data-qr');
            $('#qr-modal-body').html('<img src="' + src + '" width="300"/>');
            $('#qr-pay-modal-common').modal('show');
        });
    },
    showZDItemPrint: function(ids) {
        for(var ele in ids) {
            var id  = ids[ele];
            $('#zd-item-' + id + ' span.label-print').removeClass('hide').show();
        }
    },
    bindPayAmountChange: function(dom) {
        var self    = this;
        $(dom).bind('keyup change', function() {
            self.reCountUserPay();
        });
    },
    reCountUserPay: function() {
        var paymentAmount   = 0;
        var payMoney        = parseFloat($('#need-pay-money').val());
        $('input.payment-money').each(function() {
            var val     = $(this).val();
            val         = !val ? 0 : parseFloat(val);
            paymentAmount += val;
        });
        var zhaoLing    = (paymentAmount - payMoney).toFixed(2);
        $('#payment-amount').html('￥' + paymentAmount);
        $('#zhaoling-money').text('￥' + zhaoLing);
        $('#zhaoling-value').val(zhaoLing);
    },
    bindBtnAddPayment: function() {
        var t           = (new Date()).getTime();
        var self        = this;
        $('#btn-add-payment').click(function() {
            var tpl     = $('#payment-item-tpl').html();
            $('#append-payment-list-box').append(tpl.replace(/{t}/g, t));
            self.bindBtnSubPayment(t);
            self.bindPayAmountChange('#user-payment-list-box div.payment-' + t + ' input.payment-money');
            self.bindPaymentTypeChange();
            t ++;
        });
    },
    bindBtnSubPayment: function(t) {
        $('#btn-sub-payment-' + t).click(function() {
            var id  = $(this).attr('data-id');
            $('div.payment-' + id).remove();
        });
    },
    initSelectEffect: function(dom) {
        HHJsLib.importCss([cdnUrl + "/jquery/plugins/chosen/chosen.css"]);
        HHJsLib.importJs([cdnUrl + "/jquery/plugins/chosen/chosen.jquery.js"], function() {
            $(dom).chosen({no_results_text: "没有找对应内容!"}); 
        });
    },
    bindGuaDanBtnConfirm: function(id) {
        $('#btn-tui-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#guadan-user-id', '挂单客户');
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/order/aguadan',
                    {
                        id: id, 
                        user_id: $('#guadan-user-id').val(), 
                        comment: $('#comment').val(),
                        type: $('#guadan-type').val()
                    },
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('挂单设置成功！');
                        $('#myModal').modal('hide');
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnStuffOrder: function() {
        var self    = this;
        $('a.btn-stuff-order').click(function() {
            var id  = $(this).attr('data-id');
            var uid = $(this).attr('data-uid');
            var amount      = $(this).attr('data-amount');
            var sum         = $(this).attr('data-sum');
            var stuffTpl    = $('#stuff-order-tpl').html();
            stuffTpl        = stuffTpl.replace(/{uid}/g, uid)
            .replace(/{amount}/g, amount)
            .replace(/{sum}/g, sum);
            $('#modal-title').html('员工代点订单切换<small>（VIP会员自动使用VIP价计算）</small>');
            $('#modal-body').html(stuffTpl);
            $('#modal-footer').html($('#user-pay-footer-tpl').html());
            $('#myModal').modal('show');
            self.bindBtnSearchUser(id);
            self.bindUseLingQianYouHuiJuanChange();
        });
    },
    //员工代点餐时的订单改价功能
    bindUseLingQianYouHuiJuanChange: function() {
        var self        = this;
        $('#btn-user-chongzhi').click(function() {
            var amount  = parseFloat($('#amount').text());
            var money   = parseFloat($(this).attr('data-money'));
            var sum     = parseFloat($('#order-sum').val());
            var sub     = money > sum ? money - sum : 0;
            sub         = sub.toFixed(2);
            if(amount <= 0 && $('#user-chongzhi').is(':checked')) {
                return false;
            }
            if($('#user-chongzhi').is(':checked')) {
                $('#user-chongzhi-money').text((money - sub).toFixed(2));
                $('#user-chongzhi-txt').text(sub);
            } else {
                $('#user-chongzhi-money').text('0');
                $('#user-chongzhi-txt').text(money);
            }
            self.reCountAmount();
        });
        $('#btn-user-lingqian').click(function() {
            var amount  = parseFloat($('#amount').text());
            var money   = parseFloat($(this).attr('data-money'));
            var sum     = parseFloat($('#order-sum').val());
            var sub     = money > sum ? money - sum : 0;
            sub         = sub.toFixed(2);
            if(amount <= 0 && $('#user-lingqian').is(':checked')) {
                return false;
            }
            if($('#user-lingqian').is(':checked')) {
                $('#user-lingqian-money').text(money - sub);
                $('#user-lingqian-txt').text(sub);
            } else {
                $('#user-lingqian-money').text('0');
                $('#user-lingqian-txt').text(money);
            }
            self.reCountAmount();
        });
    },
    reCountAmount: function() {
        var sum     = parseFloat($('#order-sum').val());
        var lingQian= parseFloat($('#user-lingqian-money').text());
        var chongZhi= parseFloat($('#user-chongzhi-money').text());
        var youHuiJuan  = parseFloat($('#user-youhuijuan-money').text());
        var amount      = sum - lingQian - chongZhi - youHuiJuan;
        amount          = 0 >= amount ? 0.00 : amount;
        $('#amount').text(amount.toFixed(2));
    },
    bindBtnSearchUser: function(id) {
        var self    = this;
        $('#btn-search-user').click(function() {
            try { 
                HHJsLib.isEmptyByDom('#query', '搜索关键字');
                HHJsLib.isEmptyByDom('#s-type', '搜索类别');
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/user/asearchforpay', 
                    {query: $('#query').val(), id: id, type: $('#s-type').val()},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        self.setUserYouHuiJuanList(response.data.youhuijuan);
                        var avatar = '<img width="64" height="64" style="border-radius: 50%;" src="' 
                        + response.data.userInfo.avatar + '" /><br/>' + response.data.userInfo.name
                        + '（真实姓名：' + response.data.userInfo.true_name + '）';
                        $('#user-info-box').html(avatar);
                        $('#to-user-id').val(response.data.userInfo.id);
                        $('#user-lingqian-txt').html(response.data.userInfo.lingqian);
                        $('#user-chongzhi-txt').html(response.data.userInfo.chongzhi);
                        $('#btn-user-lingqian').attr('data-money', response.data.userInfo.lingqian);
                        $('#btn-user-chongzhi').attr('data-money', response.data.userInfo.chongzhi);
                        self.bindYHJChange();
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindYHJChange: function() {
        var self        = this;
        $('#yd-zhuohao-list').bind('change blur', function() {
            var id      = $('#yd-zhuohao-list').val();
            var money   = $('#yd-zhuohao-list').find("option:selected").attr('data-sub-money');
            $('#user-youhuijuan-money').text(money);
            self.reCountAmount();
        });
    },
    setUserYouHuiJuanList: function(list) {
        var opt     = '<option value="">请选择</option>';
        if(!list || 1 > list.length) {
            $('#yd-zhuohao-list').html(opt);
            return;
        }
        for(var ele in list) {
            opt     += '<option value="' + list[ele].id + '"'
            + 'data-sub-money="' + list[ele].sub_money + '"'
            + ' data-min-money="'+ list[ele].min_money + '">减'
            + list[ele].sub_money + '元，满' + list[ele].min_money +  '元</option>';
        }
        $('#yd-zhuohao-list').html(opt);
    },
    bindModalHide: function() {
        $('#myModal').on('hidden', function () {
            $('#modal-title').html('');
            $('#modal-body').html('');
            $('#modal-footer').html('');
        });
    },
    bindBtnCaiStart: function() {
        $('a.btn-cai-start').click(function() {
            var $this   = $(this);
            var $parent = $this.parent();
            var id      = $this.attr('data-id');
            var uid     = $this.attr('data-uid');
            if(!confirm('确认要执行此操作，此桌开始上菜了吗？')) {
                return;
            }
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/diancan/acaistart',
                {id: id, uid: uid},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('确认开始上菜成功！');
                    $this.fadeOut('fast', function() {
                        $this.remove();
                        $parent.find('a.btn-cai-done').show();
                    });
                }
            );
        });
    },
    bindBtnCaiDone: function() {
        $('a.btn-cai-done').click(function() {
            var $this   = $(this);
            var id      = $this.attr('data-id');
            var uid     = $this.attr('data-uid');
            if(!confirm('确认要执行此操作，此桌上菜完成了吗？')) {
                return;
            }
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/diancan/acaidone',
                {id: id, uid: uid},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('确认完成上菜成功！');
                    $this.fadeOut('fast', function() {
                        $this.remove();
                    });
                }
            );
        });
    },  
    bindPaiDuiStartTime: function() {
        var $item   = $('#data-grid-box-paidui span.start-time');
        if(1 > $item.length) {
            return;
        }
        var time    = parseInt((new Date()).getTime() / 1000);
        var timer   = setInterval(function() {
            $item.each(function() {
                var startTime   = $(this).attr('data-time');
                var subTime     = time - startTime;
                var min         = Math.floor(subTime / 60);
                min             = min < 0 ? 0 : min;
                var sec         = subTime - min * 60;
                sec             = sec < 0 ? 0 : sec;
                var minStr      = min > 9 ? min : '0' + min;
                var secStr      = sec > 9 ? sec : '0' + sec;
                var addClass    = min < 15 ? 'label-info' : (min < 30 ? 'label-warning' : 'label-danger');
                $(this).addClass(addClass).html(minStr + ":" + secStr);
                time ++;
            });
        }, 1000);
    },
    bindBtnCancel: function() {
        var self    = this;
        $('a.btn-cancel').click(function() {
            var id          = $(this).attr('data-id');
            if(!confirm('您真的要取消当前订单吗？注意：取消后不可恢复哦！')) {
                return;
            }
            HHJsLib.info('正在取消订单，请稍等...');
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/order/atrash',
                {id: id},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    //还原到空闲状态.
                    self.removeOrderItemBox(id);
                    $('#zhuo-hao-order-box-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                    HHJsLib.succeed('取消成功！');
                    self.setFirstActiveZhuoHao();
                }
            );
        });
    },
    setFirstActiveZhuoHao: function() {
        var $curZhuoHao = $('#zhuohao-list-box a.active').first();
        if(1 > $curZhuoHao.length) {
            return;
        }
        var title   = $('title').text();
        $curZhuoHao.click();
        history.pushState({page: 1}, title, queryUrl + 'admin/yuding?id=' + $curZhuoHao.attr('data-id'));
    },
    removeOrderItemBox: function(id) {
        $('#zhuohao-item-box-' + id).fadeOut('fast', function() {
            $(this).remove();
        });
    },
    bindTimer: function(dom) {
        dom     = typeof(dom) == 'undefined' ? 'strong.time-box' : dom;
        var $dom        = $(dom);
        var time        = Math.floor((new Date()).getTime() / 1000);
        var timer       = setInterval(function() {
            $dom.each(function() {
                var $that       = $(this);
                var startTime   = $that.attr('data-time');
                var lastTime    = time - startTime;
                var min         = Math.floor(lastTime / 60);
                var sec         = lastTime - min * 60;
                var minStr      = min >= 10 ? min : (min <= 0 ? '00' : '0' + min);
                var secStr      = sec >= 10 ? sec : (sec <= 0 ? '00' : '0' + sec);
                $that.html(minStr + ':' + secStr);
                if(min > 45) {
                    $that.removeClass('label-info').addClass('label-danger');
                } else if(min > 25) {
                    $that.removeClass('label-info').addClass('label-warning');
                }
            });
            time ++;
        }, 1000);
    },
    bindBtnTui: function(){
        var self    = this;
        $('a.btn-tui').click(function(){
            var that    = $(this);
            var id      = that.attr('data-id');
            var goodsId = that.attr('data-goods-id');
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(goodsId, '编号');
                $('#modal-title').html('退菜');
                var tpl     = $('#tui-content-tpl').html();
                var footer  = $('#tui-footer-tpl').html();
                var name    = that.parents('tr').children('td:eq(0)').children('strong.name').text();
                var price   = that.parents('tr').children('td:eq(1)').text();
                var number  = that.parents('tr').children('td:eq(5)').text();
                tpl         = tpl.replace(/{goods_name}/ig, name).replace(/{price}/ig, price)
                            .replace(/{number}/ig, number).replace(/{id}/ig, id).replace(/{order-goods-id}/ig, goodsId);
                $('#modal-body').html(tpl);
                $('.modal-footer').html(footer);
                $('#myModal').modal('show');
                self.bindBtnTuiConfirm();
            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnTuiConfirm: function(){
        $('#btn-tui-confrim').click(function(){
            var that    = $(this);
            var id      = $('#tui-goods').find('.order-id').val();
            var goodsId = $('#tui-goods').find('.order-goods-id').val();
            var oldNum  = parseInt($('#tui-goods').find('.number').val());
            var number  = parseInt($('#tui-goods').find('.goods-number').val());
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(goodsId, '编号');
                if(1 > number || number > oldNum){
                    return HHJsLib.warn('要退数量不正确');
                }                
                HJZCommon.isLoading     = true;
                HHJsLib.info('正在努力退菜中...');
                $.getJSON(
                    queryUrl + 'admin/diancan/atui',
                    {id: id, goods_id: goodsId, number: number},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('退菜成功');
                        $('#myModal').modal('hide');
                        if(number < oldNum){
                            var price = (oldNum - number) * response.data.price;
                            $('#zd-od-item-' + goodsId).children('td:eq(4)').html(oldNum - number);
                            $('#zd-od-item-' + goodsId).children('td:eq(5)').html(price.toFixed(2));
                        }else{
                            $('#zd-od-item-' + goodsId).fadeOut('fast', function(){
                                $(this).remove();
                            });                                
                        }
                        $('#item-total-number-' + id).html(response.data.number);
                        $('#item-total-amount-' + id).html(response.data.amount);
                        $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                        $('#item-total-src-amount-' + id).html(response.data.src_amount);
                        $('#item-pay-money-' + id).html(response.data.pay_money);
                        if(parseFloat(response.data.youhui) > 0){
                            $('#use-youhui-' + id).html('优惠：' + response.data.youhui + ' 元 ').show();
                        }else{
                            $('#use-youhui-' + id).hide();
                        }
                    }
                );
            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnPlus: function(){
        var self = this;
        $('a.btn-add-cai').click(function() {
            var id          = $(this).attr('data-id');
            var zhuoHaoId   = $(this).attr('data-zhuohao-id');
            $('#add-cai-title').html($('#zhuo-hao-item-' + zhuoHaoId + " h3.title").text() + '客人加菜或点单');
            $('#add-cai-modal').modal('show');
            $('#cur-order-id').val(id);
            setTimeout(function() {
                $('#btn-cai-query').val('').focus();
            }, 1000);
        });
        $('a.btn-plus').click(function(){
            var that    = $(this);
            var id      = that.attr('data-id');
            var orderId = $('#cur-order-id').val();
            var caiNumber  = $(this).parent().siblings('.cai-number').children('.add-cai-number').val();
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(orderId, '餐桌号');
                if(HJZCommon.isLoading == true) {
                    return;
                }
                HHJsLib.isEmpty(caiNumber, '数量');
                HJZCommon.isLoading = true;
                HHJsLib.info('正在操作加菜中，请稍等...');
                $.getJSON(
                    queryUrl + 'admin/diancan/aplus',
                    {id: id, order_id: orderId, number: caiNumber},
                    function(response){
                        HJZCommon.isLoading = false;
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('加菜操作成功！');
                        var data    = response.data;
                        var tpl     = $('#plus-goods-item-tpl').html();
                        tpl         = tpl.replace(/{order_goods_id}/ig, data.goods_id)
                        .replace(/{id}/ig, orderId)
                        .replace(/{name}/ig, data.name)
                        .replace(/{price}/ig, data.price)
                        .replace(/{vip_price}/ig, data.vip_price)
                        .replace(/{src_price}/ig, data.src_price)
                        .replace(/{number}/ig, data.number)
                        .replace(/{order_id}/ig, orderId)
                        .replace(/{order_goods_id}/ig, data.id)
                        .replace(/{printer_id}/ig, data.printer_id)
                        .replace(/{number}/ig, data.number)
                        .replace(/{discount}/ig, data.discount)
                        .replace(/{total_price}/ig, data.total_price);
                        $('#data-grid-box-' + orderId).find('tbody').prepend(tpl);
                        $('#item-total-number-' + orderId).html(data.total_number);
                        $('#item-total-amount-' + orderId).html(data.amount);
                        $('#item-total-src-amount-' + orderId).html(data.src_amount);
                        $('#item-pay-money-' + orderId).html(data.pay_money);
                        if(parseFloat(data.youhui) > 0){
                            $('#use-youhui-' + orderId).html('优惠：' + response.data.youhui + ' 元 ').show();
                        }else{
                            $('#use-youhui-' + orderId).hide();
                        }
                        $('#plus-goods-item-' + id).addClass('hide');
                        self.bindResetPrint('#zd-od-item-' + data.goods_id + ' a.btn-reset-print');
                        self.bindBtnPrintCai('#zd-od-item-' + data.goods_id + ' a.btn-print-cai');
                        self.bindBtnTui();
                    }
                );

            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnCaiQuery: function(){
        $('#btn-cai-query').keyup(function(event){
            var that        = $(this);
            var keyword     = that.val();
            var ids         = new Array();
            var words       = new Array();
            for(var index in goodsList){
                var item = goodsList[index];
                if((item.first_word.indexOf(keyword.toUpperCase()) >= 0) || item.name.indexOf(keyword) >= 0){
                    ids.push(item.id);
                    words.push(item.first_word);
                }
            }
            $('#add-cai-modal').find('ul.nav-tabs li').removeClass('active');
            $('#add-cai-modal').find('ul.nav-tabs li:first').addClass('active');
            $('#add-cai-modal').find('div.tab-pane').removeClass('active');
            $('#goods-cat-item-0').addClass('active');
            $('#goods-cat-item-0').find('tr.plus-goods-item')
            .addClass('hide').removeClass('search-done');
            for(var index in ids){
                var id = ids[index];
                $('#plus-goods-item-' + id).removeClass('hide').addClass('search-done');
            }
        }).bind('keydown', function(e) {
            if (e.keyCode != 13) {
                return;
            }
            $('#goods-cat-item-0 tr.search-done').first().find('a.btn-plus').click();
        });
    }
});
